package com.dingreading.cloud.app.controller;

import com.dingreading.cloud.app.entity.*;
import com.dingreading.cloud.app.mapper.BooksMapper;
import com.dingreading.cloud.app.service.*;
import com.dingreading.cloud.app.util.BooksUtil;
import com.dingreading.cloud.app.util.UidUtil;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.dto.AliyunBookDto;
import com.dingreading.cloud.common.util.AccountUtil;
import com.dingreading.cloud.common.util.DateUtil;
import com.dingreading.cloud.common.util.EnumType;
import com.dingreading.cloud.common.util.NepUtil;
import com.dingreading.cloud.common.util.aliyun.AliyunBookUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/app/memberActionLog")
@Api(tags = "APP-会员行为记录管理")
public class AppMemberActionLogController {

    @Resource
    private CorporationsService corporationsService;
    @Resource
    private MembersService membersService;
    @Resource
    private BooksService booksService;
    @Resource
    private BooksMapper booksMapper;
    @Resource
    private StoreBooksService storeBooksService;
    @Resource
    private MemberActionLogService memberActionLogService;

    @ApiOperation(value = "添加会员读书记录")
    @PostMapping(value = "/saveMemberReadBookLog")
    public R<Object> saveMemberReadBookLog(
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "会员uid") @RequestParam(value = "memberUid") String memberUid,
            @ApiParam(value = "书本的isbn编号") @RequestParam(value = "isbn") String isbn
    ) {
//        Object store = UidUtil.getStore(storeUid);
//        if (store instanceof String) return R.fail(store.toString());
//        Stores stores = (Stores) store;
//
//        Object member = UidUtil.getMember(memberUid);
//        if (member instanceof String) return R.fail(member.toString());
//        Members members = (Members) member;
//
//        Books books = new Books();
//        StoreBooks storeBooks = new StoreBooks();
//        Date datetime = DateUtil.getNowDatetime();
//
//        List<StoreBooks> storeBooksList = storeBooksService.getByStoreIdAndIsbnOrBookNum(stores.getId(), isbn);
//        if (CollectionUtils.isNotEmpty(storeBooksList)) {
//            storeBooks = storeBooksList.get(0);
//            if (storeBooks.getBooksId() != null) {
//                books = booksService.getById(storeBooks.getBooksId());
//            }
//        } else {
//            List<Books> booksList = booksService.getByIsbnOrBookNum(isbn);
//            if (CollectionUtils.isEmpty(booksList)) {
//                // 判断是否是自营门店
//                if (AccountUtil.isSelfStore((stores.getCorpUid()))) {
//                    AliyunBookDto aliyunBookDto = AliyunBookUtil.findBook(isbn);
//                    if (aliyunBookDto == null) {
//                        return R.fail("查询后书籍不存在，请联系导读员");
//                    } else {
//                        String status = aliyunBookDto.getStatus();
//                        if (status == null || !status.equals("0")) {
//                            return R.fail(AliyunBookUtil.getMessage(status));
//                        }
//                        AliyunBookDto.ResultDTO resultDTO = aliyunBookDto.getResult();
//                        if (resultDTO == null) {
//                            return R.fail("书籍不存在，请联系导读员");
//                        }
//                        // 获取书号
//                        Books maxBooks = booksService.getMaxBookNum();
//                        String bookNum = null;
//                        try {
//                            bookNum = BooksUtil.getBookNum(maxBooks);
//                        } catch (Exception e) {
//                            return R.fail("获取最新书号错误");
//                        }
//                        //新增书籍
//                        books = new Books();
//                        books.setBookName(resultDTO.getTitle());
//                        books.setAuthor(resultDTO.getAuthor());
//                        books.setImg(resultDTO.getPic());
//
//                        double price = AliyunBookUtil.getPrice(resultDTO.getPrice());
//                        books.setUnitPrice(price);
//
//                        books.setPress(resultDTO.getPublisher());
//                        books.setPubDate(resultDTO.getPubdate());
//                        books.setSynopsis(resultDTO.getSummary());
//                        books.setIsbn(isbn);
//                        books.setBookNum(bookNum);
//                        books.setSource(2);
//                        books.setSourceStoreId(stores.getId());
//                        books.setStatus(1);
//                        books.setAddTime(datetime);
//                        booksMapper.insert(books);
//                        if (books == null) {
//                            return R.fail("添加书籍失败");
//                        }
//                        storeBooks = BooksUtil.newStoreBooks(books, stores.getId(), datetime, 2);
//                        storeBooksService.saveOrUpdate(storeBooks);
//                    }
//                } else {
//                    return R.fail("查询后书籍不存在，请联系导读员");
//                }
//            } else {
//                books = booksList.get(0);
//                storeBooks = BooksUtil.newStoreBooks(books, stores.getId(), datetime, 1);
//                storeBooksService.saveOrUpdate(storeBooks);
//            }
//        }
//
//        // 添加数据
//        addLog(stores, members, books, storeBooks);
//
//        return R.ok();
        return R.fail("功能已暂停，请升级App版本");
    }

    @ApiOperation(value = "app添加会员读书记录")
    @PostMapping(value = "/v2/saveMemberReadBookLog")
    public R<Object> saveMemberReadBookLogV2(
            @ApiParam(value = "手机系统 1.安卓 2.ios") @RequestParam(value = "os") Integer os,
            @ApiParam(value = "设备标识") @RequestParam(value = "deviceId") String deviceId,
            @ApiParam(value = "版本号") @RequestParam(value = "versionCode") Integer versionCode,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "会员uid") @RequestParam(value = "memberUid") String memberUid,
            @ApiParam(value = "书本的isbn编号") @RequestParam(value = "isbn") String isbn
    ) {
        Object store = UidUtil.getStore(storeUid);
        if (store instanceof String) return R.fail(store.toString());
        Stores stores = (Stores) store;

        Object member = UidUtil.getMember(memberUid);
        if (member instanceof String) return R.fail(member.toString());
        Members members = (Members) member;

        Corporations corporations = corporationsService.getByUid(stores.getCorpUid());
        String judgeCorp = UidUtil.judgeCorp(corporations);
        if (StringUtils.isNotBlank(judgeCorp))
            return R.fail(judgeCorp);

        Books books = null;
        StoreBooks storeBooks = null;
        Date datetime = DateUtil.getNowDatetime();

        List<StoreBooks> storeBooksList = storeBooksService.getByStoreIdAndIsbnOrBookNum(stores.getId(), isbn);
        if (CollectionUtils.isNotEmpty(storeBooksList)) {
            storeBooks = storeBooksList.get(0);
            if (storeBooks.getBooksId() != null) {
                books = booksService.getById(storeBooks.getBooksId());
            }
        } else {
            List<Books> booksList = booksService.getByIsbnOrBookNum(isbn);
            if (CollectionUtils.isEmpty(booksList)) {
                // 判断是否是自营门店
                if (AccountUtil.isSelfStore((stores.getOperationType()))) {
                    AliyunBookDto aliyunBookDto = AliyunBookUtil.findBook(isbn);
                    if (aliyunBookDto == null) {
                        return R.fail("查询后书籍不存在，请联系导读员");
                    } else {
                        String status = aliyunBookDto.getStatus();
                        if (status == null || !status.equals("0")) {
                            return R.fail(AliyunBookUtil.getMessage(status));
                        }
                        AliyunBookDto.ResultDTO resultDTO = aliyunBookDto.getResult();
                        if (resultDTO == null) {
                            return R.fail("书籍不存在，请联系导读员");
                        }
                        // 获取书号
                        Books maxBooks = booksService.getMaxBookNum();
                        String bookNum = null;
                        try {
                            bookNum = BooksUtil.getBookNum(maxBooks);
                        } catch (Exception e) {
                            return R.fail("获取最新书号错误");
                        }
                        //新增书籍
                        books = new Books();
                        books.setBookName(resultDTO.getTitle());
                        books.setAuthor(resultDTO.getAuthor());
                        books.setImg(resultDTO.getPic());

                        double price = AliyunBookUtil.getPrice(resultDTO.getPrice());
                        books.setUnitPrice(price);

                        books.setPress(resultDTO.getPublisher());
                        books.setPubDate(resultDTO.getPubdate());
                        books.setSynopsis(resultDTO.getSummary());
                        books.setIsbn(isbn);
                        books.setBookNum(bookNum);
                        books.setSource(2);
                        books.setSourceStoreId(stores.getId());
                        books.setStatus(1);
                        books.setAddTime(datetime);
                        booksMapper.insert(books);
                        if (books == null) {
                            return R.fail("添加书籍失败");
                        }
                        storeBooks = BooksUtil.newStoreBooks(books, stores.getId(), datetime, 2);
                        storeBooksService.saveOrUpdate(storeBooks);
                    }
                } else {
                    return R.fail("查询后书籍不存在，请联系导读员");
                }
            } else {
                books = booksList.get(0);
                storeBooks = BooksUtil.newStoreBooks(books, stores.getId(), datetime, 1);
                storeBooksService.saveOrUpdate(storeBooks);
            }
        }

        // 添加数据
        addLog(stores, members, books, storeBooks);

        return R.ok();
    }

    private void addLog(Stores stores, Members members, Books books, StoreBooks storeBooks) {
        //更新会员的读书本数
        Integer readBooks = NepUtil.nullToZero(members.getReadBooks()) + 1;
        members.setReadBooks(readBooks);
        membersService.saveOrUpdate(members);

        // 添加阅读记录
        MemberActionLog memberActionLog = new MemberActionLog();
        memberActionLog.setActionType(EnumType.ActionType.READ_BOOK.getType());
        memberActionLog.setCorpUid(stores.getCorpUid());
        memberActionLog.setStoreId(stores.getId());
        memberActionLog.setStoreUid(stores.getUid());
        memberActionLog.setStoreName(stores.getStoreName());
        memberActionLog.setMemberId(members.getId());
        memberActionLog.setMemberUid(members.getUid());
        memberActionLog.setFullName(members.getFullName());
        memberActionLog.setMemberName(members.getMemberName());

        if (null != storeBooks) {
            memberActionLog.setBookImg(storeBooks.getImg());
            memberActionLog.setBookName(storeBooks.getBookName());
            memberActionLog.setIsbn(storeBooks.getIsbn());
            memberActionLog.setBookNum(storeBooks.getBookNum());
            memberActionLog.setAuthor(storeBooks.getAuthor());
            memberActionLog.setBookLabelId(storeBooks.getBookLabelId());
            memberActionLog.setBookLabelName(storeBooks.getBookLabelName());
            memberActionLog.setBookTypeId(storeBooks.getBookTypeId());
            memberActionLog.setBookType(storeBooks.getBookType());
        } else {
            if (null != books) {
                memberActionLog.setBooksId(books.getId());
                memberActionLog.setBookImg(books.getImg());
                memberActionLog.setBookName(books.getBookName());
                memberActionLog.setIsbn(books.getIsbn());
                memberActionLog.setBookNum(books.getBookNum());
                memberActionLog.setAuthor(books.getAuthor());
                memberActionLog.setBookLabelId(books.getBookLabelId());
                memberActionLog.setBookLabelName(books.getBookLabelName());
                memberActionLog.setBookTypeId(books.getBookTypeId());
                memberActionLog.setBookType(books.getBookType());
            }
        }
        if (null != storeBooks) {
            memberActionLog.setStoreBookId(storeBooks.getId());
        }
        memberActionLog.setStatus(1);
        memberActionLog.setReadTime(DateUtil.getNowDatetime());
        memberActionLogService.saveOrUpdate(memberActionLog);
    }

}